package service

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

var Auth = new(serviceMiddleware)

type serviceMiddleware struct {}

type jwtCustomClaims struct {
	jwt.StandardClaims
	// 追加自己需要的信息
	AppId int `json:"app_id"`
	Secret string `json:"secret"`
}

/**
生成token
 */
func (s *serviceMiddleware) CreateToken(issuer string, Uid int, seckey string) (tokenString string, err error) {
	claims := &jwtCustomClaims{
		jwt.StandardClaims{
			ExpiresAt: int64(time.Now().Add(time.Hour * 72).Unix()),
			Issuer: issuer,
		},
		Uid,
		seckey,
	}
	SecretKey := []byte(seckey)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err = token.SignedString(SecretKey)
	return
}

/**
解析token
 */
func (s *serviceMiddleware) ParseToken(tokenSrt string, SecretKey []byte) (claims jwt.Claims, err error) {

	token, err := jwt.Parse(tokenSrt, func(*jwt.Token) (interface{}, error) {
		return SecretKey, nil
	})
	if err != nil {
		return nil, err
	}
	claims = token.Claims
	return claims, nil
}